/*
 * XMLNameSpace.cpp
 *
 *  Created on: May 27, 2018
 *      Author: hp
 */

#include <stdlib.h>
#include <string.h>

#include "android-xml.h"

#include "ResStringPool.h"
#include "XMLNameSpace.h"

XMLNameSpace::XMLNameSpace() {
}

XMLNameSpace::XMLNameSpace(const ResStringPool& string_pool, const char* data) {
	ResXMLTree_node header;
	memcpy(&header, data, sizeof(ResXMLTree_node));

	ResXMLTree_namespaceExt namespaceext;
	memcpy(&namespaceext, data + header.header.headerSize,
			sizeof(ResXMLTree_namespaceExt));

	_name = strdup(string_pool.get(namespaceext.prefix.index));
	_uri = strdup(string_pool.get(namespaceext.uri.index));
}

uint32_t XMLNameSpace::serialize(ResStringPool& string_pool, char** data) {
	uint32_t datasize = sizeof(ResXMLTree_node)
			+ sizeof(ResXMLTree_namespaceExt);
	*data = (char*) malloc(datasize);

	ResXMLTree_node* header = (ResXMLTree_node*) *data;
	ResXMLTree_namespaceExt* namespaceext =
			(ResXMLTree_namespaceExt*) ((char*) *data + sizeof(ResXMLTree_node));

	header->comment.index = -1;
	header->lineNumber = ++g_lineno;
	header->header.headerSize = sizeof(ResXMLTree_node);
	header->header.size = datasize;
	header->header.type = RES_XML_START_NAMESPACE_TYPE;

	namespaceext->prefix = string_pool.put(_name);
	namespaceext->uri = string_pool.put(_uri);
	// string_pool.put_empty();
	return datasize;
}

uint32_t XMLNameSpace::serialize_end(ResStringPool& string_pool, char** data) {
	uint32_t datasize = sizeof(ResXMLTree_node)
			+ sizeof(ResXMLTree_namespaceExt);
	*data = (char*) malloc(datasize);

	ResXMLTree_node* header = (ResXMLTree_node*) *data;
	ResXMLTree_namespaceExt* namespaceext =
			(ResXMLTree_namespaceExt*) ((char*) *data + sizeof(ResXMLTree_node));

	header->comment.index = -1;
	header->lineNumber = ++g_lineno;
	header->header.headerSize = sizeof(ResXMLTree_node);
	header->header.size = datasize;
	header->header.type = RES_XML_END_NAMESPACE_TYPE;

	namespaceext->prefix = string_pool.put(_name);
	namespaceext->uri = string_pool.put(_uri);

	return datasize;
}

const char* XMLNameSpace::get(const char* uri) const {
	if (strcmp(_uri, uri) == 0) {
		return _name;
	}

	return nullptr;
}

XMLNameSpace::~XMLNameSpace() {
	free((void*) _name);
	free((void*) _uri);
}

